package com.icesoft.core.web.suppose.safehttp.config;

import com.icesoft.core.common.helper.AnnotationUtil;
import com.icesoft.core.common.helper.Resp;
import com.icesoft.core.common.util.JsonUtil;
import com.icesoft.core.web.suppose.safehttp.SafeRequest;
import com.icesoft.core.web.suppose.safehttp.SafeRequestConst;
import com.icesoft.core.web.suppose.safehttp.filter.SafeRequestCryptoService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
@AllArgsConstructor
@Order
@Slf4j
public class SafeRequestResponseBodyAdvice implements ResponseBodyAdvice<Object> {
    private final SafeRequestCryptoService safeRequestCryptoService;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        SafeRequest safeRequest = AnnotationUtil.findAnyAnnotation(returnType.getMethod(), SafeRequest.class);
        return SafeRequestConst.isEncrypt(safeRequest);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
                                  ServerHttpResponse response) {
        if (request instanceof ServletServerHttpRequest && body != null) {
            if (!(body instanceof Resp)) {
                return Resp.error("响应值要求必须是Resp类型");
            }
            Resp<?> resp = (Resp<?>) body;
            log.debug("响应resp ：{}",resp);
            if (resp.getData() != null) {
                Resp<String> respCopy = new Resp<>();
                respCopy.setCode(resp.getCode());
                respCopy.setMsg(resp.getMsg());
                String jsonData = JsonUtil.toJson(resp.getData());
                log.trace("原始响应resp.data json ：{}",jsonData);
                respCopy.setData(safeRequestCryptoService.encryptRespData(jsonData));
                body = respCopy;
            }
        }
        safeRequestCryptoService.clearSign();
        return body;
    }

}
